//
//  FSDropDownMenu.m
//  FSDropDownMenu
//
//  Created by xiang-chen on 14/12/17.
//  Copyright (c) 2014年 chx. All rights reserved.
//
#import "AVOSManger.h"
#import "FSDropDownMenu.h"

#import "CategoryCollectionViewCell.h"
//#import "CategoryCollectionViewController.h"

@interface FSDropDownMenu()


@property (nonatomic, assign) BOOL show;
@property (nonatomic, assign) CGPoint origin;
@property (nonatomic, assign) CGFloat height;
@property (nonatomic, strong) UIView *backGroundView;

@property (nonatomic, strong) NSArray *images;
@property (nonatomic, strong) NSArray *titles;
@property (nonatomic, strong) UIButton *button;

@end

#define ScreenWidth      CGRectGetWidth([UIScreen mainScreen].applicationFrame)

@implementation FSDropDownMenu
@synthesize mainCollectionView,button,selectedIndexPath;
#pragma mark - init method
- (instancetype)initWithOrigin:(CGPoint)origin andHeight:(CGFloat)height{
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    self = [self initWithFrame:CGRectMake(origin.x, 0, screenSize.width, _height)];
    if (self) {
        _origin = origin;
        _show = NO;
        _height = height;
        
        if(!self.mainCollectionView)
        {
            UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc]init];
            
            [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
            flowLayout.itemSize = CGSizeMake(100, 100);
            CGFloat leftInset = (screenSize.width -  flowLayout.itemSize.width*3)/4;
            //flowLayout.minimumInteritemSpacing = 0;
            //flowLayout.minimumLineSpacing= 50;
            flowLayout.sectionInset = UIEdgeInsetsMake(20,leftInset, 0, 0);
            
            mainCollectionView = [[UICollectionView alloc] initWithFrame:self.frame collectionViewLayout:flowLayout];
            mainCollectionView.delegate =self;
            mainCollectionView.dataSource = self;
            mainCollectionView.backgroundColor = [UIColor whiteColor];
            

            //regist cell identifier
            [mainCollectionView registerNib:[UINib nibWithNibName:@"CategoryCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"Category"];
        }
        
        [self addSubview:self.mainCollectionView];
        
        //self tapped
        self.backgroundColor = [UIColor whiteColor];
        
        //background init and tapped
        _backGroundView = [[UIView alloc] initWithFrame:CGRectMake(origin.x, origin.y, screenSize.width, screenSize.height)];
        _backGroundView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.0];
        _backGroundView.opaque = NO;
        UIGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backgroundTapped:)];
        [_backGroundView addGestureRecognizer:gesture];
        
        //add bottom shadow
        UIView *bottomShadow = [[UIView alloc] initWithFrame:CGRectMake(0, self.frame.size.height-0.5, screenSize.width, 0.5)];
        bottomShadow.backgroundColor = [UIColor lightGrayColor];
        [self addSubview:bottomShadow];
        
        
        //Data init
        self.images = @[[UIImage imageNamed:@"QB"],[UIImage imageNamed:@"JX"],[UIImage imageNamed:@"PH"],[UIImage imageNamed:@"DSN"],[UIImage imageNamed:@"YDH"],[UIImage imageNamed:@"QPX"],[UIImage imageNamed:@"GN"],[UIImage imageNamed:@"GW"]];
        
        self.titles = @[@"全部",@"逗死你",@"国内",@"精选",@"微热门",@"国外",@"排行",@"奇葩"];
    }
    
    return self;
}




- (void)addCloseBtn{
    button = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [button setBackgroundImage:[UIImage imageNamed:@"Close_Normal"] forState:UIControlStateNormal];
    
    [button setFrame:CGRectMake(0, self.frame.size.height , 40, 40)];
    
    [button addTarget:self action:@selector(backgroundTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    button.translatesAutoresizingMaskIntoConstraints = NO;
    
    //NSNumber* height = [NSNumber numberWithFloat:_height];
    
    
    [self.mainCollectionView addSubview:button];
    
    [self.mainCollectionView addConstraint:[NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.mainCollectionView attribute:NSLayoutAttributeBottom multiplier:1 constant:_height - 15]];
    
        [self.mainCollectionView addConstraint:[NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.mainCollectionView attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]];
    
    //[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(>10)-button" options:NSLayoutFormatAlignAllBottom metrics:nil views:NSDictionaryOfVariableBindings(button,_backGroundView)]];
    
    
}

#pragma mark - gesture handle
- (void)menuTapped:(void(^)())completion{
    if(!self.button)
    {
        //if the device screen height < 1136 then not add the close button
    if([TLDeviceManger deviceScreenSize].height > 1136)
    [self addCloseBtn];
        
    [self animateBackGroundView:self.backGroundView show:!_show complete:^{
        [self animateTableViewShow:!_show complete:^{
            
//            _show = !_show;
            
            completion();
        }];
     }];
   }
}

- (void)backgroundTapped:(UITapGestureRecognizer *)paramSender
{
    [self animateBackGroundView:_backGroundView show:NO complete:^{
        [self animateTableViewShow:NO complete:^{
            _show = NO;
        }];
    }];
}

#pragma mark - animation method
- (void)animateBackGroundView:(UIView *)view show:(BOOL)show complete:(void(^)())complete {
    if (show) {
        [self.superview addSubview:view];
        [view.superview addSubview:self];
        
        [UIView animateWithDuration:0.2 animations:^{
            view.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.4];
        }];
    } else {
        [UIView animateWithDuration:0.2 animations:^{
            view.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.0];
        } completion:^(BOOL finished) {
            [view removeFromSuperview];
        }];
    }
    complete();
}

- (void)animateTableViewShow:(BOOL)show complete:(void(^)())complete {
    if (show) {
        [self.superview addSubview:mainCollectionView];
        [UIView animateWithDuration:0.5 animations:^{
            mainCollectionView.alpha = 1.f;
            mainCollectionView.frame = CGRectMake(self.origin.x, self.origin.y, ScreenWidth, _height);
            if (self.transformView) {
                self.transformView.transform = CGAffineTransformMakeRotation(M_PI);
            }
        } completion:^(BOOL finished) {
            [self dropViewDelegateChanged];
            complete();
        }];
    } else {
        [UIView animateWithDuration:0.5 animations:^{
            mainCollectionView.alpha = 0.f;
            if (self.transformView) {
                self.transformView.transform = CGAffineTransformMakeRotation(0);
            }
        } completion:^(BOOL finished) {
            [self dropViewDelegateChanged];
            complete();
        }];
    }
    
}

- (void)dropViewDelegateChanged{
    if([self.delegate respondsToSelector:@selector(dropViewDidChanged:)])
    {
        [self.delegate dropViewDidChanged:_show];
    }
}
#pragma mark - table delegate

#pragma mark - table datasource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if(section != 2)
    return 3;
    else
    return 2;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CategoryCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Category" forIndexPath:indexPath];
    
    if(!cell)
    {
        NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"CategoryCollectionViewCell" owner:self options:nil];
        if(nibs.count > 0)
        {
        cell = [nibs lastObject];
        }
    }
    NSUInteger indexOfCell = (indexPath.section * 3 + indexPath.row);
    
    UIImage *image = [self.images objectAtIndex:indexOfCell];
    
    [cell.cellImgBtn setBackgroundImage:image forState:UIControlStateNormal];
    
    [cell.cellNameLabel setText:[self.titles objectAtIndex:indexOfCell]];
    
    return cell;
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 3;
}

- (void)collectionView:(nonnull UICollectionView *)collectionView didSelectItemAtIndexPath:(nonnull NSIndexPath *)indexPath{
    NSAssert(self.delegate != nil, @"menu's dataSource shouldn't be nil");
    if ([self.delegate respondsToSelector:@selector(menu:collectionView:didSelectIndex:title:)]) {
         NSUInteger indexOfSelectCell = (indexPath.section * 3 + indexPath.row);
        [self.delegate menu:self collectionView:mainCollectionView didSelectIndex:indexOfSelectCell title:self.titles[indexOfSelectCell]];
        [self menuTapped:^{
            [self backgroundTapped:nil];
        }];
    } else {
        NSAssert(0 == 1, @"required method of dataSource protocol should be implemented");
    }
}
- (void)setSelectedIndexPath:(NSIndexPath *)selectedIndexPath_{
    selectedIndexPath = selectedIndexPath_;
    //NSLog(@"%@",[self.mainCollectionView visibleCells ]);
    /*
    CategoryCollectionViewCell *targetCell =(CategoryCollectionViewCell *)[self.mainCollectionView cellForItemAtIndexPath:selectedIndexPath_];
    
    [targetCell showBottomLine:YES animated:YES completion:^{
        
    }];
     */
}

/*
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSAssert(self.dataSource != nil, @"menu's dataSource shouldn't be nil");
    if ([self.dataSource respondsToSelector:@selector(menu:tableView:numberOfRowsInSection:)]) {
        return [self.dataSource menu:self tableView:tableView
                numberOfRowsInSection:section];
    } else {
        NSAssert(0 == 1, @"required method of dataSource protocol should be implemented");
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"DropDownMenuCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    NSAssert(self.dataSource != nil, @"menu's datasource shouldn't be nil");
    if ([self.dataSource respondsToSelector:@selector(menu:tableView:titleForRowAtIndexPath:)]) {
        cell.textLabel.text = [self.dataSource menu:self tableView:tableView titleForRowAtIndexPath:indexPath];
    } else {
        NSAssert(0 == 1, @"dataSource method needs to be implemented");
    }
    if(tableView == _leftTableView){
        cell.backgroundColor = [UIColor whiteColor];
    }else{
        UIView *sView = [[UIView alloc] init];
        sView.backgroundColor = [UIColor whiteColor];
        cell.selectedBackgroundView = sView;
        [cell setSelected:YES animated:NO];
        cell.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1.f];
    }
    cell.textLabel.font = [UIFont systemFontOfSize:14.0];
    cell.separatorInset = UIEdgeInsetsZero;
    

    
    return cell;
}

#pragma mark - tableview delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.delegate || [self.delegate respondsToSelector:@selector(menu:tableView:didSelectRowAtIndexPath:)]) {
        if (tableView == self.leftTableView) {
            [self animateBackGroundView:_backGroundView show:NO complete:^{
                [self animateTableViewShow:NO complete:^{
                    _show = NO;
                }];
            }];
        }
        [self.delegate menu:self tableView:tableView didSelectRowAtIndexPath:indexPath];
    } else {
        //TODO: delegate is nil
    }
}
 */

@end
